const path = require('path');
const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const { glob } = require('glob');
const webpack = require('webpack');
const nodeExternals = require('webpack-node-externals');

// 获取当前环境
const env = process.env.NODE_ENV || 'production';
console.log(`当前构建环境: ${env}`);

// 异步函数获取入口文件
async function getEntries() {
  const entries = {};
  const srcDir = path.resolve(__dirname, 'src');
  
  // 使用glob v11的异步API
  const tsFiles = await glob('**/*.ts', { cwd: srcDir });
  
  // 为每个ts文件创建一个入口点
  tsFiles.forEach(file => {
    const entryName = file.replace(/\.ts$/, '');
    entries[entryName] = path.resolve(srcDir, file);
  });
  
  return entries;
}

// 创建webpack配置
async function createConfig() {
  const entries = await getEntries();
  
  // 基础配置
  const config = {
    // 指定为Node.js环境
    target: 'node',
    
    // 使用多入口配置
    entry: entries,
    
    // 输出配置
    output: {
      path: path.resolve(__dirname, 'dist'),
      filename: '[name].js',
      clean: true // 构建前清理输出目录
    },
    
    // 将所有node_modules中的模块设为外部依赖，不打包进bundle
    externals: [nodeExternals()],
    
    // 解析配置
    resolve: {
      extensions: ['.ts', '.js'],
      // 使用tsconfig-paths-webpack-plugin处理路径别名
      plugins: [new TsconfigPathsPlugin()],
      // 添加fallback配置，处理缺失的依赖
      fallback: {
        "osx-temperature-sensor": false
      }
    },
    
    // 模块配置
    module: {
      rules: [
        {
          test: /\.ts$/,
          use: {
            loader: 'ts-loader',
            options: {
              // 启用transpileOnly可以提高构建速度，但会跳过类型检查
              // 如果需要类型检查，可以移除此选项或设置为false
              transpileOnly: env !== 'production'
            }
          },
          exclude: /node_modules/
        }
      ]
    },
    
    // 使用环境变量中的值，如果未指定则默认为'production'
    mode: env,
    
    // 节点环境配置
    node: {
      // 保留__dirname和__filename的行为
      __dirname: false,
      __filename: false
    },
    
    // 插件配置
    plugins: [
      // 复制模板和静态资源
      new CopyWebpackPlugin({
        patterns: [
          { from: 'src/templates', to: 'templates' },
          { from: 'src/sql', to: 'sql', noErrorOnMissing: true },
          { from: 'public', to: 'public', noErrorOnMissing: true },
          // 添加以下配置，复制package.json、pnpm-lock.yaml和环境配置文件到dist目录
          { from: 'package.json', to: 'package.json' },
          { from: 'pnpm-lock.yaml', to: 'pnpm-lock.yaml', noErrorOnMissing: true },
          { from: '.env', to: '.env', toType: 'file', noErrorOnMissing: true },
          { from: '.env.development', to: '.env.development', toType: 'file', noErrorOnMissing: true },
          { from: '.env.production', to: '.env.production', toType: 'file', noErrorOnMissing: true }
        ]
      }),
      // 忽略PostgreSQL相关模块
      new webpack.IgnorePlugin({
        resourceRegExp: /^pg-hstore$|^pg$/,
        contextRegExp: /sequelize/
      }),
      // 定义环境变量，确保打包后的代码使用正确的NODE_ENV
      new webpack.DefinePlugin({
        'process.env.NODE_ENV': JSON.stringify(env)
      })
    ],
    
    // 生产环境优化
    optimization: {
      minimize: false, // 不压缩代码
      // 分块策略
      splitChunks: {
        chunks: 'all',
        // 提取公共模块
        cacheGroups: {
          commons: {
            name: 'commons',
            chunks: 'initial',
            minChunks: 2
          }
        }
      }
    },
    
    // 根据环境配置sourcemap
    devtool: env === 'production' ? 'source-map' : 'eval-source-map',
    
    // 性能提示
    performance: {
      hints: env === 'production' ? 'warning' : false
    },
    
    // 统计信息
    stats: {
      colors: true,
      modules: false,
      children: false,
      chunks: false,
      chunkModules: false
    }
  };

  return config;
}

// 导出配置
module.exports = createConfig(); 